package edu.del.springbootredisbusinesspractice.service.init;


import edu.del.springbootredisbusinesspractice.mapper.ProductMapper;
import edu.del.springbootredisbusinesspractice.pojo.Product;
import edu.del.springbootredisbusinesspractice.service.impl.CacheService;
import edu.del.springbootredisbusinesspractice.utils.cachekey.CacheConstants;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class StockCacheInitializer {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CacheService cacheService;

    @PostConstruct
    public void init() {
        List<Product> products = productMapper.selectList(null);
        for (Product product : products) {
            String stockKey = String.format(CacheConstants.STOCK_KEY_PREFIX, product.getId());
            redisTemplate.opsForValue().set(stockKey, String.valueOf(product.getStock()));
            // 本地缓存
            cacheService.getStockCache().put(stockKey, (long) product.getStock());
            log.info("【初始化库存缓存】商品ID: {}, 库存: {}", product.getId(), product.getStock());
        }
    }
}